package com.example.smart.base.dialog.base

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.*
import androidx.viewbinding.ViewBinding
import com.example.smart.R
import com.example.smart.base.listener.OnBaseDialogBackListener
import com.example.smart.base.listener.OnBaseDialogDismissListener
import com.example.smart.base.utils.getViewBinding

/**
 * 基类弹窗
 */
abstract class BaseDialog<V : ViewBinding>(
    var height: Int = WindowManager.LayoutParams.WRAP_CONTENT,
    var width: Int = WindowManager.LayoutParams.WRAP_CONTENT,
    val gravity: Int = Gravity.CENTER,
    val animRes: Int = 0,
    val dialogContext: Context,
    val style: Int = R.style.dialogStyle,
) : Dialog(dialogContext, style) {
    lateinit var binding: V
    private val dismissListener = mutableListOf<OnBaseDialogDismissListener>()
    private var backListener: OnBaseDialogBackListener? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        setDialogLayout()
        setOnDismissListener {
            dismissListener.forEach { it.onDismiss() }
        }
    }

    /**
     * 初始化视图
     */
    private fun initView() {
        val layoutRes = setLayoutRes()
        if (layoutRes != 0) {
            val view = LayoutInflater.from(context).inflate(layoutRes, null)
            binding = getViewBinding(view)
            afterViewCreate(view)
            setContentView(view)
            setDialogLayout()
        } else {
            throw NullPointerException("dialog layout resource be #0x0")
        }
    }

    /**
     * 重新配置弹窗尺寸
     */
    private fun setDialogLayout() {
        val window = window
        if (window != null) {
            window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
            window.decorView.setPadding(0, 0, 0, 0)
            val params = window.attributes
            params.width = width
            params.height = height
            params.dimAmount = 0.8f
            window.attributes = params
            window.setGravity(gravity)
            window.setWindowAnimations(animRes)
        }
    }

    /**
     * 添加布局资源
     *
     * @return 布局资源
     */
    abstract fun setLayoutRes(): Int

    /**
     * 视图创建完成
     *
     * @param view 当前视图
     */
    abstract fun afterViewCreate(view: View?)

    /**
     * 禁止取消
     */
    open fun banCancel() {
        setCanceledOnTouchOutside(false)
        setCancelable(false)
    }

    /**
     * 禁止点击外部取消
     */
    open fun banTouchCancel() {
        setCanceledOnTouchOutside(false)
    }

    fun setOnBackListener(listener: OnBaseDialogBackListener) {
        backListener = listener
    }

    fun addDismissListener(listener: OnBaseDialogDismissListener) {
        dismissListener.add(listener)
    }

    fun clearDismissListener() {
        dismissListener.clear()
    }

    override fun dispatchKeyEvent(event: KeyEvent): Boolean {
        return backListener?.let {
            if (event.action == KeyEvent.ACTION_DOWN) {
                if (event.keyCode == KeyEvent.KEYCODE_BACK) it.onKeyDown(event) || it.onBack()
                else it.onKeyDown(event)
            } else if (event.action == KeyEvent.ACTION_UP) {
                it.onKeyUp(event)
            }
            super.dispatchKeyEvent(event)
        } ?: super.dispatchKeyEvent(event)
    }

    override fun show() {
        if (!isShowing) {
            if (dialogContext is Activity) {
                if (dialogContext.isDestroyed.not()) super.show()
            } else super.show()
        }
    }

    override fun dismiss() {
        if (isShowing) {
            if (dialogContext is Activity) {
                if (dialogContext.isDestroyed.not()) super.dismiss()
            } else super.dismiss()
        }
    }
}